package com.jinzhi.jinzhidata.controller;

import com.jinzhi.jinzhidata.enums.ResultEnum;
import com.jinzhi.jinzhidata.util.Constant;
import com.jinzhi.jinzhidata.util.JwtUtil;
import com.jinzhi.jinzhidata.util.ResultVOUtil;
import com.jinzhi.jinzhidata.util.UUIDUtil;
import com.jinzhi.jinzhidata.vo.ResultVO;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description
 * @date 2020-01-11 19:23
 **/
@RequestMapping("/editor")
@RestController
public class EditorController {


    @PostMapping(value = "/image")
    @ResponseBody
    public ResultVO uploadImage(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        String userId = JwtUtil.verifyAccessToken(request, response);
        System.out.println("id为" + userId + "的用户上传图片");
        if (userId == null) {
            return ResultVOUtil.error(ResultEnum.NOT_LOGIN);
        }
        if (file.isEmpty()) {
            return ResultVOUtil.error(ResultEnum.ATTACHMENT_EMPTY_ERROR);
        }
        String imageName;
        try {
            String originImageName = file.getOriginalFilename();
            String coverSuffix = originImageName.substring(originImageName.lastIndexOf(".") + 1);
            imageName = UUIDUtil.getUUID() + "." + coverSuffix;
            file.transferTo(new File(Constant.IMAGE_FILE_DIRECTORY + imageName));
        } catch (IOException e) {
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.ATTACHMENT_UPLOAD_FAILED);
        }
        Map<String, String> res = new HashMap<>();
        res.put("src", "/img/" + imageName);
        res.put("title", imageName);
        return ResultVOUtil.success(res);
    }
}
